import React, { Component } from 'react';
import { Button, Balloon } from '@teamix/ui';
import { ButtonIcon, YunxiaoIcon } from '@alife/devops-ui';
import docs from 'utils/docs';
import { PROJECT_WRITE_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import ListEmpty from 'atComponents/ListEmpty';
import { navigate } from 'utils/router';
import UploadFile from './content/dialog/uploadFile';
import track from 'utils/track';
import utils from 'utils/index';
import intl from '../../../../../../../locale';

const { user, pathResource, resourceSubject } = window.FORCE;
const invalidMailSuffix = '@mail.teambition.com';

const DisabledTootip = (props) => {
  const { isArchive } = pathResource;
  const { trigger } = props;
  if (isArchive !== 'true') {
    return trigger;
  }
  return (
    <Balloon.Tooltip trigger={trigger} align="t">
      {intl.get({
        id: 'code-assets.projectFiles.containers.empty.TheCodeLibraryHasBeen',
        defaultMessage: '代码库已归档，不允许提交新内容',
      })}
    </Balloon.Tooltip>
  );
};

export default class Empty extends Component {
  state = {
    openKeys: ['one', 'two', 'three'],
    isDialogVisible: false,
  };

  onDialogClose = () => {
    this.setState({
      isDialogVisible: false,
    });
  };

  onNewFile = (file_name = '') => {
    const { isArchive } = pathResource;
    if (isArchive === 'true') {
      return;
    }
    const revision = resourceSubject.revision || pathResource.defaultBranch || 'master';
    track({
      action: file_name ? 'new_readme' : 'new_file',
      page: 'Empty-Repo',
      type: '',
      control: '',
    });

    navigate(`/${pathResource.fullPath}/new/${revision}/?file_name=${file_name}`);

    // 按照\src\pages\index\actions\index.js 调用updateSetSelectedType处理
    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'new',
        path: '',
      },
    });
  };

  toggleKeys = (value) => {
    const { openKeys } = this.state;
    const index = openKeys.findIndex((item) => {
      return item === value;
    });
    if (index > -1) {
      openKeys.splice(index, 1);
    } else {
      openKeys.push(value);
    }
    this.setState({
      openKeys,
    });
  };

  showUploadFile = () => {
    const { isArchive } = pathResource;
    if (isArchive === 'true') {
      return;
    }
    track({
      action: 'import_file',
      page: 'Empty-Repo',
      type: '',
      control: '',
    });

    this.setState({
      isDialogVisible: true,
    });
  };

  render() {
    const { projectInfo, cloneWay } = this.props;
    const { role } = pathResource;
    const projectName =
      pathResource.fullPath.split('/')[pathResource.fullPath.split('/').length - 1];
    const { openKeys, isDialogVisible } = this.state;

    let { email } = user;
    if (utils.endsWith(email, invalidMailSuffix)) {
      email = intl.get({
        id: 'code-assets.projectFiles.containers.empty.YourEmailAddress',
        defaultMessage: '你的邮箱',
      });
    }

    const dataSource = [
      {
        title: 'SSH',
        address: projectInfo.ssh_url_to_repo,
      },

      {
        title: 'HTTPS',
        address: projectInfo.http_url_to_repo,
      },
    ];

    const curAddress = dataSource.find((item) => item.title === cloneWay).address;

    const hasAccess = access(PROJECT_WRITE_ROLES, role);

    const isArchive = pathResource.isArchive === 'true';

    return (
      <>
        <ListEmpty
          title={intl.get({
            id: 'code-assets.projectFiles.containers.empty.TheCodeLibraryIsEmpty',
            defaultMessage: '代码库空空如也～',
          })}
          description={intl.get({
            id: 'code-assets.projectFiles.containers.empty.YouCanCreateAFile',
            defaultMessage:
              '你可以新建文件或使用 Git 命令关联已有代码文件，开始分支管理、安全检测、代码评审与合并等操作',
          })}
          image="none"
        />

        {hasAccess && (
          <div className="empty-init-project">
            <div className="empty-title">
              {intl.get({
                id: 'code-assets.projectFiles.containers.empty.QuickInitialization',
                defaultMessage: '快速初始化',
              })}
            </div>
            <div className="empty-init-cards">
              <DisabledTootip
                trigger={
                  <div
                    className={`empty-init-cards-item ${isArchive ? 'disabled' : ''}`}
                    onClick={() => {
                      this.onNewFile('README.md');
                    }}
                  >
                    <div>
                      <ButtonIcon name="add-line" type="primary" disabled={isArchive} />
                    </div>
                    <div className="content">
                      <div className="title">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.CreateReadme',
                          defaultMessage: '新建 Readme',
                        })}
                      </div>
                      <div className="desc">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.UseReadmeMdToInitialize',
                          defaultMessage: '使用 Readme.md 一键初始化工程',
                        })}
                      </div>
                    </div>
                    <div className="empty-init-cards-item-bg" />
                  </div>
                }
              />

              <DisabledTootip
                trigger={
                  <div
                    className={`empty-init-cards-item ${isArchive ? 'disabled' : ''}`}
                    onClick={() => {
                      this.onNewFile();
                    }}
                  >
                    <div>
                      <ButtonIcon name="add-line" type="primary" disabled={isArchive} />
                    </div>
                    <div className="content">
                      <div className="title">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.CreateAFile',
                          defaultMessage: '新建文件',
                        })}
                      </div>
                      <div className="desc">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.ExcellentCodeStartingWithThe',
                          defaultMessage: '卓越的代码，从第一个文件开始',
                        })}
                      </div>
                    </div>
                    <div className="empty-init-cards-item-bg" />
                  </div>
                }
              />

              <DisabledTootip
                trigger={
                  <div
                    className={`empty-init-cards-item ${isArchive ? 'disabled' : ''}`}
                    onClick={this.showUploadFile}
                  >
                    <div>
                      <ButtonIcon name="add-line" type="primary" disabled={isArchive} />
                    </div>
                    <div className="content">
                      <div className="title">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.UploadObjects',
                          defaultMessage: '上传文件',
                        })}
                      </div>
                      <div className="desc">
                        {intl.get({
                          id: 'code-assets.projectFiles.containers.empty.FastUploadOfLocalFiles',
                          defaultMessage: '极速上传本地文件',
                        })}
                      </div>
                    </div>
                    <div className="empty-init-cards-item-bg" />
                  </div>
                }
              />
            </div>
          </div>
        )}

        <div className="empty-wrapper">
          <h3 className="empty-title mt40">
            {intl.get({
              id: 'code-assets.src.utils.locale.CommandLineGuide',
              defaultMessage: '命令行指引',
            })}
          </h3>
          <div className="git-empty">
            <div className="title">
              {intl.get({
                id: 'code-assets.projectFiles.containers.empty.ToIdentifyTheIdentityWe',
                defaultMessage: '为了标识身份，建议先完成 Git 全局设置',
              })}
            </div>
            <pre className="light-well way-content user-info">
              git config --global user.name {`"${user.nickname}"`}
              <br />
              git config --global user.email {`"${email}"`}
            </pre>
            <div className="way-one way">
              <Button
                type="normal"
                text
                color="gray"
                onClick={() => {
                  this.toggleKeys('one');
                }}
              >
                <YunxiaoIcon
                  type={openKeys.includes('one') ? 'trilateral-down-fill' : 'trilateral-right-fill'}
                  style={{ marginRight: 8 }}
                />
                <span>
                  {intl.get({
                    id: 'code-assets.projectFiles.containers.empty.MethodCloneARepository',
                    defaultMessage: '方式一：克隆仓库',
                  })}
                </span>
              </Button>
            </div>
            <pre
              className="light-well way-content"
              style={{ display: openKeys.includes('one') ? 'block' : 'none' }}
            >
              git clone <span className="clone">{curAddress}</span>
              <br />
              cd {projectName}
              <br />
              touch README.md
              <br />
              git add README.md
              <br />
              git commit -m {'"add README"'}
              <br />
              git push -u origin master
            </pre>
            <div className="way-two way">
              <Button
                type="normal"
                text
                color="gray"
                onClick={() => {
                  this.toggleKeys('two');
                }}
              >
                <YunxiaoIcon
                  type={openKeys.includes('two') ? 'trilateral-down-fill' : 'trilateral-right-fill'}
                  style={{ marginRight: 8 }}
                />
                <span>
                  {intl.get({
                    id: 'code-assets.projectFiles.containers.empty.MethodExistingFoldersOrRepositories',
                    defaultMessage: '方式二：已有文件夹或仓库',
                  })}
                </span>
              </Button>
            </div>
            <pre
              className="light-well way-content"
              style={{ display: openKeys.includes('two') ? 'block' : 'none' }}
            >
              cd existing_folder
              <br />
              git init
              <br />
              git remote add origin <span className="clone">{curAddress}</span>
              <br />
              git add .
              <br />
              git commit
              <br />
              git push -u origin master
            </pre>
            <div className="way-two way">
              <Button
                type="normal"
                text
                color="gray"
                onClick={() => {
                  this.toggleKeys('three');
                }}
              >
                <YunxiaoIcon
                  type={
                    openKeys.includes('three') ? 'trilateral-down-fill' : 'trilateral-right-fill'
                  }
                  style={{ marginRight: 8 }}
                />
                <span>
                  {intl.get({
                    id: 'code-assets.projectFiles.containers.empty.MethodImportTheCodeLibrary',
                    defaultMessage: '方式三：导入代码库',
                  })}
                </span>
              </Button>
            </div>
            <pre
              className="light-well way-content"
              style={{ display: openKeys.includes('three') ? 'block' : 'none' }}
            >
              git clone --bare https://git.example.com/your/project.git your_path
              <br />
              cd your_path
              <br />
              git remote set-url origin <span className="clone">{curAddress}</span>
              <br />
              git push --mirror
            </pre>
          </div>
          <div className="empty-more">
            {intl.get({
              id: 'code-assets.projectFiles.containers.empty.NeedMoreFunctionalDescriptionsAnd',
              defaultMessage: '需要更多功能说明和 Git 教程？请参看',
            })}{' '}
            <a href={docs('gitTeachingQuickStart')} target="blank">
              {intl.get({
                id: 'code-assets.projectFiles.containers.empty.HelpManual',
                defaultMessage: '帮助手册',
              })}
            </a>
          </div>
        </div>
        {isDialogVisible ? (
          <UploadFile
            {...this.props}
            closeModal={this.onDialogClose}
            isDialogVisible={isDialogVisible}
          />
        ) : null}
      </>
    );
  }
}
